package cn.wgoodq.controller;

/**
 * Created by OuKyou on 2017/1/11.
 */

import cn.wgoodq.domain.Result;
import cn.wgoodq.domain.User;
import cn.wgoodq.service.userService.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {
    private final UserService userService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    String login(Model model) {
        model.addAttribute("user", new User());
        return "login/signin";
    }

    @GetMapping("/index")
    String index(Model model) {
        return "index";
    }

    @PostMapping("/signin")
    String signin(HttpServletRequest request, Model model, @ModelAttribute("user") User user) {
        Result<User> rtnParam = userService.signin(user);

        if (rtnParam.isSuccess()) {
            model.addAttribute("userName", rtnParam.getData().getUserName());

            //记住我功能
            if (user.isRmm()) {
                logger.debug("user.isRmm=true;write {} to sesseion.", rtnParam.getData());
                request.getSession().setAttribute("user", rtnParam.getData());
            }

            // 登录成功，跳转到主页
            return "redirect:/index";
        } else {
            // 返回登录失败信息
            model.addAttribute("failedMsg", rtnParam.getMsg());

            // 登录失败，回到登录页面
            return "forward:/";
        }
    }
}